import pandas as pd
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.neural_network import MLPRegressor
from sklearn.svm import SVR
import joblib

month_map = {
    'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04',
    'may': '05', 'jun': '06', 'jul': '07', 'aug': '08',
    'sep': '09', 'oct': '10', 'nov': '11', 'dec': '12'
}


def convert_date(date_str):
    month = month_map[date_str.lower()]
    return month


df = pd.read_csv('杭州市.csv', encoding='gbk')
df[['日', '月份']] = df['商品采价日期'].str.split('-', expand=True)
df['月份'] = df['月份'].apply(convert_date).astype(int)
df['日'] = df['日'].astype(int)

df = pd.get_dummies(df, columns=['商品主键'], prefix='商品主键')

X = df.drop(['商品采价日期', '商品采价地区编码', '商品价格', '商品销量', '销售额'], axis=1)
y = df['商品价格']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

# 训练随机森林回归模型
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# 模型评估
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"随机森林模型评估: MSE = {mse:.4f}, R² = {r2:.4f}")
# 保存模型

model2 = GradientBoostingRegressor(
    n_estimators=100,
    learning_rate=0.1,
    random_state=42
)
model2.fit(X_train, y_train)

y_pred = model2.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"GB模型评估: MSE = {mse:.4f}, R² = {r2:.4f}")

svm_model = SVR(C=100, kernel='linear', gamma='scale')
svm_model.fit(X_train, y_train)

y_pred = svm_model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"SVR模型评估: MSE = {mse:.4f}, R² = {r2:.4f}")

mlp_model = MLPRegressor(hidden_layer_sizes=(100, 50), activation='relu', solver='adam', random_state=42, max_iter=500)
mlp_model.fit(X_train, y_train)

y_pred = mlp_model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"mlp模型评估: MSE = {mse:.4f}, R² = {r2:.4f}")

# ---------------
from sklearn.model_selection import GridSearchCV

param_grid = {
    'hidden_layer_sizes': [(50,), (100,50), (150,100,50)],
    'alpha': [0.0001, 0.001, 0.01],  # L2正则化系数
    'learning_rate_init': [0.001, 0.01, 0.1],
}

grid_search = GridSearchCV(
    MLPRegressor(activation='relu', solver='adam', random_state=42, max_iter=500),
    param_grid,
    cv=5,  # 5折交叉验证
    scoring='neg_mean_squared_error'
)
grid_search.fit(X_train, y_train)
